const redis = require("redis");
const config = require("../../config/config")["redis"];
let rclient = null;
module.exports = {
  init() {
    rclient = redis.createClient(config.port, config.host, config.opt);

    rclient.auth(config.pwd, function () {
      console.log("redis通过认证");
    });
    rclient.on("connect", function () {
      console.log("redis连接成功");
    });
  },

  // 设置key值
  set(key, value, expire = 0) {
    if (!rclient) {
      this.init();
    }

    rclient.set(key, value); //赋值
    if (expire) {
      rclient.expire(key, expire); //60秒自动过期
    }
  },

  get(key) {
    if (!rclient) {
      this.init();
    }

    return new Promise((resolve, reject) => {
      rclient.get(key, function (err, data) {
        resolve(data);
      });
    });
  },
};
